#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"

int main() {
    // 从本地 JSON 文件中读取数据
    FILE *file = fopen("data.json", "r");
    if (file == NULL) {
        perror("Error opening JSON file");
        exit(EXIT_FAILURE);
    }

    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);

    char *json_data = (char *)malloc(file_size + 1);
    fread(json_data, 1, file_size, file);
   

    // 解析 JSON 数据
    cJSON *root = cJSON_Parse(json_data);
    free(json_data);

    if (root == NULL) {
        printf("Error parsing JSON\n");
        exit(EXIT_FAILURE);
    }

    // 修改age字段为98
    cJSON *person = cJSON_GetObjectItem(root, "person");
    cJSON *age = cJSON_GetObjectItem(person, "age");
    printf("age00: %d\n", age->valueint);
    if (age != NULL) {
        cJSON_ReplaceItemInObject(person, "age", cJSON_CreateNumber(98));
    }
    cJSON *age1 = cJSON_GetObjectItem(person, "age");
    if (age1 != NULL) {
    printf("Modified age1: %d\n", age1->valueint);
    }
    printf("age11: %d\n", age1->valueint);

    fclose(file);
    #if 1
    // 保存 JSON 数据到本地
    char *json_string = cJSON_Print(root);
    FILE *output_file = fopen("data.json", "w");
    if (output_file == NULL) {
        perror("Error opening output file");
        exit(EXIT_FAILURE);
    }
    fprintf(output_file, "%s", json_string);
    fclose(output_file);
    free(json_string);
    #endif

    // 释放 JSON 对象
    cJSON_Delete(root);

    return 0;
}